<template>
  <div class="news-form">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ isEdit ? '编辑新闻' : '创建新闻' }}</h2>
        <p>{{ isEdit ? '修改新闻内容' : '发布新的新闻内容' }}</p>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <!-- 左侧主要内容 -->
        <el-col :span="16">
          <el-card title="基本信息">
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入新闻标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="摘要" prop="summary">
              <el-input
                v-model="form.summary"
                type="textarea"
                :rows="3"
                placeholder="请输入新闻摘要"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="封面图片">
              <div class="cover-upload">
                <el-upload
                  class="cover-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="handleUpload"
                >
                  <img v-if="form.coverImage" :src="form.coverImage" class="cover-image" />
                  <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tips">
                  <p>建议尺寸：800x450px，支持 JPG、PNG 格式，大小不超过 2MB</p>
                  <el-button v-if="form.coverImage" size="small" type="danger" @click="removeCover">
                    删除封面
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="正文内容" prop="content">
              <div class="editor-container">
                <el-input
                  v-model="form.content"
                  type="textarea"
                  :rows="20"
                  placeholder="请输入新闻正文内容，支持HTML格式"
                />
                <div class="editor-tips">
                  <p>支持HTML标签，如：&lt;p&gt;、&lt;h1&gt;-&lt;h6&gt;、&lt;img&gt;、&lt;a&gt; 等</p>
                </div>
              </div>
            </el-form-item>
          </el-card>
        </el-col>

        <!-- 右侧设置 -->
        <el-col :span="8">
          <el-card title="发布设置">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">草稿</el-radio>
                <el-radio :label="1">发布</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="置顶">
              <el-switch v-model="form.isTop" :active-value="1" :inactive-value="0" />
            </el-form-item>

            <el-form-item label="描述">
              <el-input
                v-model="form.desc"
                type="textarea"
                :rows="3"
                placeholder="新闻描述信息（可选）"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-card>

          <!-- 预览卡片 -->
          <el-card title="预览" style="margin-top: 20px;" v-if="form.title">
            <div class="preview-card">
              <div class="preview-image" v-if="form.coverImage">
                <img :src="form.coverImage" alt="封面" />
              </div>
              <div class="preview-content">
                <h4 class="preview-title">{{ form.title }}</h4>
                <p class="preview-summary">{{ form.summary }}</p>
                <div class="preview-meta">
                  <span>{{ formatTime(new Date()) }}</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button size="large" @click="goBack">取消</el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSubmit"
              :loading="submitting"
            >
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createNews, updateNews, getNewsDetail } from '@/api/news'
import { getCategoryList } from '@/api/news'
import { Plus } from '@element-plus/icons-vue'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const formRef = ref()
const loading = ref(false)
const submitting = ref(false)
const categories = ref([])

// 表单数据
const form = reactive({
  title: '',
  summary: '',
  content: '',
  coverImage: '',
  categoryId: null,
  status: 0,
  isTop: 0,
  desc: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入新闻摘要', trigger: 'blur' },
    { min: 10, max: 200, message: '摘要长度在 10 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' },
    { min: 50, message: '内容长度至少 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择新闻分类', trigger: 'change' }
  ]
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 方法
const fetchCategories = async () => {
  try {
    categories.value = await getCategoryList()
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const fetchNewsDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const newsDetail = await getNewsDetail(route.params.id)
    Object.assign(form, {
      title: newsDetail.title,
      summary: newsDetail.summary,
      content: newsDetail.content,
      coverImage: newsDetail.coverImage,
      categoryId: newsDetail.categoryId,
      status: newsDetail.status,
      isTop: newsDetail.isTop,
      desc: newsDetail.desc || ''
    })
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    ElMessage.error('获取新闻详情失败')
  } finally {
    loading.value = false
  }
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUpload = (options) => {
  // 这里应该调用实际的上传接口
  // 现在先模拟一个上传成功的响应
  const reader = new FileReader()
  reader.onload = (e) => {
    form.coverImage = e.target.result
    ElMessage.success('上传成功')
  }
  reader.readAsDataURL(options.file)
}

const removeCover = () => {
  form.coverImage = ''
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (isEdit.value) {
      await updateNews(route.params.id, form)
      ElMessage.success('更新成功')
    } else {
      await createNews(form)
      ElMessage.success('创建成功')
    }
    
    router.push('/news')
  } catch (error) {
    if (error.errors) {
      // 表单验证错误
      return
    }
    console.error('提交失败:', error)
    ElMessage.error('提交失败：' + error.message)
  } finally {
    submitting.value = false
  }
}

const goBack = () => {
  router.push('/news')
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchCategories()
  fetchNewsDetail()
})
</script>

<style scoped>
.news-form {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-title h2 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 24px;
}

.header-title p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 封面上传 */
.cover-upload {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  display: block;
}

.upload-tips {
  flex: 1;
}

.upload-tips p {
  color: #909399;
  font-size: 12px;
  margin: 0 0 10px 0;
  line-height: 1.5;
}

/* 编辑器 */
.editor-container {
  position: relative;
}

.editor-tips {
  margin-top: 8px;
}

.editor-tips p {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

/* 预览卡片 */
.preview-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  height: 120px;
  overflow: hidden;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-content {
  padding: 15px;
}

.preview-title {
  font-size: 16px;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.preview-summary {
  color: #606266;
  font-size: 14px;
  margin: 0 0 10px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.preview-meta {
  color: #909399;
  font-size: 12px;
}

/* 操作按钮 */
.form-actions {
  margin-top: 30px;
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.form-actions .el-button {
  min-width: 100px;
}
</style>
